package service

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"sensi/app/api/dto"
	"sensi/app/model"
	"sensi/common/sys/database"
	"strings"
)

func (s *Service) ListFirmwareVersions(ctx *gin.Context) (interface{}, error) {
	list, err := s.firmVerRepo.List(database.Instance(ctx))
	if err != nil {
		return nil, err
	}

	return list, nil
}

func (s *Service) AddFirmwareVersion(ctx *gin.Context) (interface{}, error) {
	req := &dto.AddFirmwareVersionReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}

	m := &model.FirmwareVersion{
		Broadcast: req.Broadcast,
		Version:   req.Version,
		File:      req.File,
	}

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) UpdateFirmwareVersion(ctx *gin.Context) (interface{}, error) {
	req := &dto.UpdateFirmwareVersionReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.firmVerRepo.ByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty version")
	}

	m.Version = req.Version
	m.File = req.File

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) DeleteFirmwareVersion(ctx *gin.Context) (interface{}, error) {
	req := &dto.DeleteReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.firmVerRepo.ByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty dial")
	}

	if err := database.Instance(ctx).Delete(m).Error; err != nil {
		return nil, err
	}

	return nil, nil
}

func (s *Service) CompareFirmwareVersions(ctx *gin.Context) (interface{}, error) {
	req := &dto.CompareFirmwareVersionReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	resp := &dto.CompareFirmwareVersionResp{}

	m, err := s.firmVerRepo.ByBroadcast(database.Instance(ctx), req.Broadcast)
	if err != nil {
		return nil, err
	}
	if m == nil {
		resp.LatestVersion = "v0.0.0"
		return resp, nil
	}

	if strings.Compare(m.Version, req.CurrentVersion) > 0 {
		resp.IsUpgrade = true
		resp.LatestVersion = m.Version
		resp.File = m.File
	} else {
		resp.IsUpgrade = false
		resp.LatestVersion = req.CurrentVersion
	}

	return resp, nil
}
